<?php
declare(strict_types=1);
namespace App\Api;

use App\ApiController;
use OSS\Core\OssException;
use OSS\OssClient;

// hook api_upload_use.php

/**
 * @title  上传附件
 * @auth   true
 * @rank   3
 */
class Upload extends ApiController
{
    // hook api_upload_start.php

    /**
     * @title   新增上传图片
     * @rank    99
     */
    public function action_Add(){

        $fileObj=$this->request->getFiles()['upfile'];
        $filepath =$fileObj['tmp_name'];
        $ext = pathinfo($fileObj['name'], PATHINFO_EXTENSION);

        if (!in_array(strtolower($ext), array('jpeg', 'jpg', 'png', 'gif'))) {
            $this->response('0002',[
                'state'=>'error'
            ],'上传的文件不是图片');
        }

        if (!getimagesize($filepath) !== false) {
          $this->response('0002',[
              'state'=>'error'
          ],'上传的文件不是图片');
        }
        $fileName=md5($filepath.time());
        $content = file_get_contents($filepath);

        $options = array(
            OssClient::OSS_LENGTH => strlen($content),
            OssClient::OSS_HEADERS => array(
                'Expires' => 'Fri, 28 Feb 2020 05:38:42 GMT',
                'Cache-Control' => 'no-cache',
                'Content-Disposition' => 'attachment;filename=oss_download.log',
                'Content-Language' => 'zh-CN',
                'x-oss-server-side-encryption' => 'AES256',
                'x-oss-meta-self-define-title' => 'user define meta info',
            ),
        );
        $errMsg='';
        $uploadFileUrl='';
        try {
            $res=$this->ossClient->putObject(_CONF('OssBucket'), 'qbk_www/user_file/'.$fileName.'.'.$ext, $content, $options);
            if(isset($res['info']['url'])){
                $uploadFileUrl=$res['info']['url'];
            }
        } catch (\Exception $e) {
           $errMsg=$e->getMessage();
        }
        if(empty($uploadFileUrl)){
            $this->response('0003',[
                'state'=>'error'
            ],$errMsg);
        }
        $uploadFileUrl=str_replace('http://','https://',$uploadFileUrl);
        $this->response('0000',[
            'url'=>$uploadFileUrl,
            'original'=>'',
            'state'=>'SUCCESS'
        ],'上传成功');
    }
    // hook api_upload_end.php

}

?>